package middleware

import (
	"blog/types"
	util "blog/utils"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func JWT() gin.HandlerFunc {
	return func(c *gin.Context) {
		var code int
		var data interface{}
		code = types.ApiCode.SUCCESS
		token := c.GetHeader("Authorization")
		if token == "" {
			code = types.ApiCode.INVALIDTOKEN
		} else {
			claims, err := util.ParseToken(token)
			if err != nil {

				code = types.ApiCode.INVALIDTOKEN
			} else if time.Now().Unix() > claims.ExpiresAt {
				code = types.ApiCode.AUTHFAILED
			} else {
				c.Set("userId", claims.UserId)
				c.Set("appCode", claims.AppCode)
			}
		}

		if code != types.ApiCode.SUCCESS {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code": code,
				"msg":  types.ApiCode.GetMessage(code),
				"data": data,
			})

			c.Abort()
			return
		}

		c.Next()
	}
}
